<template>
  <div>
    <Card ref="card" title="新建项目">
      <p slot="title">新建项目</p>
      <a href="#" slot="extra" @click.prevent="refData">刷新</a>
      <Row>
        <Button
          size="large"
          type="primary"
          icon="ios-cloud-upload-outline"
          @click="ImportNoProject"
        >新建项目 - 导入幸福院信息</Button>

        <Button
          style="margin-left:10px"
          size="large"
          type="primary"
          icon="ios-cloud-upload-outline"
          @click="ImportHasProject"
        >导入幸福院信息到现有项目</Button>

        <Button
          style="margin-left:10px"
          size="large"
          type="primary"
          icon="ios-filing-outline"
          @click="modal3=true;"
        >新建一个空项目</Button>
      </Row>
      <Row>
        <div class="ivu-upload-list-file" v-if="file !== null">
          <Icon type="ios-stats"></Icon>
          {{ file.name }}
          <Icon
            v-show="showRemoveFile"
            type="ios-close"
            class="ivu-upload-list-remove"
            @click.native="handleRemove()"
          ></Icon>
        </div>
      </Row>
      <Row>
        <transition name="fade">
          <Progress v-if="showProgress" :percent="progressPercent" :stroke-width="2">
            <div v-if="progressPercent == 100">
              <Icon type="ios-checkmark-circle"></Icon>
              <span>成功</span>
            </div>
          </Progress>
        </transition>
      </Row>
    </Card>
    <Modal :mask-closable="false" v-model="modal1" width="500">
      <p slot="header" class="color-primary text-align-center">
        <Icon type="ios-information-circle"></Icon>
        <span>新增项目 - 导入信息</span>
      </p>

      <Form :label-width="80">
        <FormItem label="县区">
           <Select
            @on-change="getAreaValue"
            filterable
            label-in-value
            v-model="pGroup.SavedAreaId"
            size="large"
            placeholder="县区"
          >
            <Option v-for="item in areaList" :value="item.Gid" :key="item.Gid">{{ item.AreaName }}</Option>
          </Select>
        </FormItem>
        <FormItem label="年度">
          <Select v-model="pGroup.GroupYear" size="large">
            <Option v-for="item in yearList" :value="item" :key="item">{{ item }}</Option>
          </Select>
        </FormItem>
        <FormItem label="项目类别">
          <Input v-model="pGroup.GroupType" size="large" placeholder="项目类别" />
        </FormItem>
        <FormItem label="项目名称">
          <Tag color="green">{{pGroup.GroupArea}}{{pGroup.GroupYear}}{{pGroup.GroupType}}</Tag>
        </FormItem>
      </Form>

      <div slot="footer">
        <Upload action :before-upload="handleBeforeUpload" accept=".xls, .xlsx">
          <Button
            :disabled="!pGroup.GroupArea||!pGroup.GroupYear||!pGroup.GroupType"
            size="large"
            type="primary"
            icon="ios-cloud-upload-outline"
            :loading="uploadLoading"
            @click="ImportNoProjectDo"
          >导入幸福院信息</Button>
        </Upload>
      </div>
    </Modal>
    <Modal :mask-closable="false" v-model="modal2" width="500">
      <p slot="header" class="color-primary text-align-center">
        <Icon type="ios-information-circle"></Icon>
        <span>选择项目 - 导入信息</span>
      </p>

      <br />

      <Row>
        <Select
          filterable
          label-in-value
          v-model="grouptmp"
          @on-change="perChange"
          size="large"
          placeholder="请选择项目"
        >
          <Option v-for="item in grouplist" :value="item.Gid" :key="item.Gid">{{ item.GroupName }}</Option>
        </Select>
      </Row>
      <br />

      <div slot="footer">
        <Upload action :before-upload="handleBeforeUpload" accept=".xls, .xlsx">
          <Button
            :disabled="!grouptid"
            size="large"
            type="primary"
            icon="ios-cloud-upload-outline"
            :loading="uploadLoading"
            @click="ImportHasProjectDo"
          >导入幸福院信息</Button>
        </Upload>
      </div>
    </Modal>

    <Modal :mask-closable="false" v-model="modal3" width="500">
      <p slot="header" class="color-primary text-align-center">
        <Icon type="ios-information-circle"></Icon>
        <span>新建空项目</span>
      </p>

      <Form :label-width="80">
        <FormItem label="县区">
          <Select
            @on-change="getAreaValue"
            filterable
            label-in-value
            v-model="pGroup.SavedAreaId"
            size="large"
            placeholder="县区"
          >
            <Option v-for="item in areaList" :value="item.Gid" :key="item.Gid">{{ item.AreaName }}</Option>
          </Select>
        </FormItem>
        <FormItem label="年度">
          <Select v-model="pGroup.GroupYear" size="large">
            <Option v-for="item in yearList" :value="item" :key="item">{{ item }}</Option>
          </Select>
        </FormItem>
        <FormItem label="项目类别">
          <Input v-model="pGroup.GroupType" size="large" placeholder="项目类别" />
        </FormItem>
        <FormItem label="项目名称">
          <Tag color="green">{{pGroup.GroupArea}}{{pGroup.GroupYear}}{{pGroup.GroupType}}</Tag>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button
          :disabled="!pGroup.GroupArea||!pGroup.GroupYear||!pGroup.GroupType"
          type="primary"
          size="large"
          @click="SaveXFYGroup()"
        >保存</Button>
      </div>
    </Modal>
    <Row class="margin-top-10">
      <Table
        border
        :columns="tableTitle"
        :data="tableData"
        :loading="tableLoading"
        ref="table"
        :height="tableHeight"
      ></Table>
    </Row>
  </div>
</template>
<script>
import { Modal, Message } from "view-design";
import excel from "@/libs/excel";
import { SearchArea } from "@/api/data";
import {
  ImportAssessXFY,
  SearchXFYGrouphasPage,
  SaveXFYGroup,
} from "@/api/xfy";
export default {
  name: "import_xfy",
  data() {
    return {
      tableHeight: 450,
      uploadLoading: false,
      progressPercent: 0,
      showProgress: false,
      showRemoveFile: false,
      file: null,
      tableData: [],
      tableTitle: [],
      tableLoading: false,
      modal1: false,
      modal2: false,
      modal3: false,
      grouplist: [],
      grouptmp: "",
      grouptid: "",
      grouptname: "",
      pGroup: {
        GroupArea: "",
        GroupYear: "",
        GroupType: "",
        SavedAreaId: "",
      },
      yearList: [],
      areaList: [],
    };
  },
  methods: {
    perChange(e) {
      this.grouptid = e.value;
      this.grouptname = e.label;
    },
    ImportHasProject() {
      this.pGroup.GroupYear = "";
      this.pGroup.GroupType = "";
      this.modal2 = true;
    },
    ImportHasProjectDo() {
      if (this.grouptid) {
        this.pGroup.Gid = this.grouptid;
        this.pGroup.GroupName = this.grouptname;
        this.handleUploadFile();
      } else {
        this.$Modal.error({ title: "提示", content: "请选择项目" });
      }
    },
    ImportNoProject() {
      this.modal1 = true;
    },
    ImportNoProjectDo() {
      if (!this.pGroup.GroupArea) {
        this.$Modal.error({ title: "提示", content: "请选择县区" });
      } else if (!this.pGroup.GroupYear) {
        this.$Modal.error({ title: "提示", content: "请选择年度" });
      } else if (!this.pGroup.GroupType) {
        this.$Modal.error({ title: "提示", content: "请填写项目类别" });
      } else {
        this.pGroup.Gid = "";
        this.pGroup.GroupName =
          this.pGroup.GroupArea + this.pGroup.GroupYear + this.pGroup.GroupType;
        this.handleUploadFile();
      }
    },
    refData() {
      this.SearchArea();
      this.SearchXFYGrouphasPage();
    },
    getYear() {
      var date = new Date();
      var year = date.getFullYear();
      for (var i = -5; i < 6; i++) {
        var tmpYear = year + i + "年度";
        this.yearList.push(tmpYear);
      }
      this.pGroup.GroupYear = year + "年度";
    },
    SearchArea() {
      let vm = this;
      SearchArea().then((res) => {
        const data = res.data;
        if (data.Type == 1) {
          vm.areaList = data.Data;
        } else {
          Message.error(data.Message);
        }
      });
    },
    SearchXFYGrouphasPage() {
      let vm = this;
      var reqData = {
        issaved: 0,
      };
      SearchXFYGrouphasPage(reqData).then((res) => {
        const data = res.data;
        if (data.Type == 1) {
          vm.grouplist = data.Data.Rows;
        } else {
          vm.$Message.error(data.Message);
        }
      });
    },
    SaveXFYGroup() {
      let vm = this;
      if (!this.pGroup.GroupArea) {
        this.$Modal.error({ title: "提示", content: "请选择县区" });
      } else if (!this.pGroup.GroupYear) {
        this.$Modal.error({ title: "提示", content: "请选择年度" });
      } else if (!this.pGroup.GroupType) {
        this.$Modal.error({ title: "提示", content: "请填写项目类别" });
      } else {
        this.pGroup.Gid = "";
        this.pGroup.GroupName =
          this.pGroup.GroupArea + this.pGroup.GroupYear + this.pGroup.GroupType;
      }
      SaveXFYGroup(this.pGroup).then((res) => {
        const data = res.data;
        if (data.Type == 1) {
          vm.modal3 = false;
          Message.success("操作成功");
        } else {
          Message.error(data.Message);
        }
      });
    },
  getAreaValue(val) {
      this.pGroup.GroupArea = val.label;
    },
    initUpload() {
      this.file = null;
      this.showProgress = false;
      this.loadingProgress = 0;
      this.tableData = [];
      this.tableTitle = [];
    },
    handleUploadFile() {
      this.initUpload();
    },
    handleRemove() {
      this.initUpload();
      this.$Message.info("上传的文件已删除！");
    },
    handleBeforeUpload(file) {
      const fileExt = file.name.split(".").pop().toLocaleLowerCase();
      if (fileExt === "xlsx" || fileExt === "xls") {
        this.readFile(file);
        this.file = file;
      } else {
        this.$Notice.warning({
          title: "文件类型错误",
          desc:
            "文件：" +
            file.name +
            "不是EXCEL文件，请选择后缀为.xlsx或者.xls的EXCEL文件。",
        });
      }
      return false;
    },
    // 读取文件
    readFile(file) {
      var vm = this;
      const reader = new FileReader();
      reader.readAsArrayBuffer(file);
      reader.onloadstart = (e) => {
        this.uploadLoading = true;
        this.tableLoading = true;
        this.showProgress = true;
      };
      reader.onprogress = (e) => {
        this.progressPercent = Math.round((e.loaded / e.total) * 100);
      };
      reader.onerror = (e) => {
        this.$Message.error("文件读取出错");
      };
      reader.onload = (e) => {
        // this.$Message.info("文件读取成功");
        const data = e.target.result;
        const { header, results } = excel.read(data, "array");
        const tableTitle = header.map((item) => {
          return { title: item, key: item };
        });
        this.tableTitle = tableTitle;
        this.tableData = results;
        this.uploadLoading = false;
        this.tableLoading = false;
        this.showRemoveFile = true;
        var reqData = {
          pGroup: this.pGroup,
          orgList: results,
        };
        ImportAssessXFY(reqData).then((r) => {
          var data = r.data;
          if (data.Type == 1) {
            vm.modal1 = false;
            vm.modal2 = false;
            Modal.info({
              title: "提示",
              content: "幸福院信息导入成功！",
            });
            vm.SearchXFYGrouphasPage();
          } else {
            if (data.Data == null || data.Data.length <= 0) {
              Modal.error({
                title: "提示",
                content: data.Message,
              });
            } else {
              var errMsg = "导入失败！<br/>";
              data.Data.forEach((element) => {
                errMsg += element.错误信息 + "<br/>";
              });
              Modal.info({
                title: "提示",
                content: errMsg,
              });
            }
          }
        });
      };
    },
  },
  created() {},
  mounted() {
    var cardHeight = this.$refs.card.$el.offsetHeight;
    this.tableHeight = window.innerHeight - cardHeight - 160;
    this.getYear();
    this.SearchArea();
    this.SearchXFYGrouphasPage();
  },
};
</script>
